import {
	apis_network
} from "./api"
let network = apis_network;
const Url = network;

import md5 from "./md5"
let secret = 'ef4906b73a7bf35b5c586257fe732cd9';


const request = (url, data, type, content_type = true, header = {}, is_sign = false) => {

	let time = new Date().getTime();
	let paskey = wx.getStorageSync('userInfo').paskey
	let sign = md5(secret + time + paskey)

	let sign_obj = {};
	if (url.search('api/app') != -1 || url.search('api/ouyoung') != -1) {
		sign_obj = {
			apptype:getApp().globalData.apptype,
			paskey,
			time,
			sign,
		}
	}
	if (is_sign) {
		sign_obj = {
			apptype: 4,
			paskey,
			time,
			sign,
		}
	}
	console.log(Url + url)


	return new Promise((reslove, reject) => {
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: Url + url,
			data: {
				...sign_obj,
				...data
			},
			method: type,
			header: {
				'X-Token': wx.getStorageSync('merchant').token,
				"content-type": content_type ? "application/json" : "application/x-www-form-urlencoded",
				...header
			},
			success(res) {
				wx.hideLoading();
				reslove(res)
			},
			fail(err) {
				wx.hideLoading();
				console.log('--err--')
				wx.showToast({
					title: "请求超时，请稍后重试",
					icon: "none"
				})
				reject(err)
			}
		})
	})
}
const gets = (url, obj, content_type = true, header = {}, is_sign = false) => {
	return request(url, obj, 'GET', content_type, header, is_sign)
}
const posts = (url, obj, content_type = true, header = {}, is_sign = false) => {
	return request(url, obj, 'POST', content_type, header, is_sign)
}
const deletes = (url, obj, content_type = true) => {
	return request(url, obj, 'delete', content_type)
}
const uploads = (filePath) => {
	wx.showLoading({
		title: '加载中',
		mask: true
	})
	let time = new Date().getTime();
	let paskey = wx.getStorageSync('userInfo').paskey
	let sign = md5(secret + time + paskey)
	return new Promise((reslove, reject) => {
		wx.uploadFile({
			filePath: filePath,
			name: 'image',
			formData: {
				uid: wx.getStorageSync('userInfo').id,
				apptype:getApp().globalData.apptype,
				paskey,
				time,
				sign,
			},
			url: network + '/api/ouyoung/qiniuUplodeFile',
			success: (r) => {
				reslove(r)
			},
			fail: (e) => {
				wx.showToast({
					title: "上传失败，请稍后重试",
					icon: "none"
				})
				reject(e)
			},
			complete: () => {
				wx.hideLoading();
			}
		})
	})
}
module.exports = {
	posts,
	gets,
	deletes,
	uploads,
	Url
}